package repository

import (
	"context"
	"fmt"
	"time"

	"github.com/google/uuid"
	"gorm.io/gorm"
	"techoiceness.com/aiagent/llm-gateway/internal/entity"
)

// adminRepository 管理员仓库实现
type adminRepository struct {
	db *gorm.DB
}

// NewAdminRepository 创建管理员仓库
func NewAdminRepository(db *gorm.DB) AdminRepository {
	return &adminRepository{
		db: db,
	}
}

// 管理员认证相关
func (r *adminRepository) GetAdminByUsername(ctx context.Context, username string) (*entity.Admin, error) {
	var admin entity.Admin
	err := r.db.WithContext(ctx).Where("username = ?", username).First(&admin).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		}
		return nil, fmt.Errorf("failed to get admin by username: %w", err)
	}
	return &admin, nil
}

func (r *adminRepository) GetAdminByID(ctx context.Context, id uuid.UUID) (*entity.Admin, error) {
	var admin entity.Admin
	err := r.db.WithContext(ctx).Where("id = ?", id).First(&admin).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		}
		return nil, fmt.Errorf("failed to get admin by ID: %w", err)
	}
	return &admin, nil
}

// 管理员管理
func (r *adminRepository) CreateAdmin(ctx context.Context, admin *entity.Admin) error {
	err := r.db.WithContext(ctx).Create(admin).Error
	if err != nil {
		return fmt.Errorf("failed to create admin: %w", err)
	}
	return nil
}

func (r *adminRepository) UpdateAdmin(ctx context.Context, admin *entity.Admin) error {
	err := r.db.WithContext(ctx).Save(admin).Error
	if err != nil {
		return fmt.Errorf("failed to update admin: %w", err)
	}
	return nil
}

func (r *adminRepository) DeleteAdmin(ctx context.Context, id uuid.UUID) error {
	err := r.db.WithContext(ctx).Delete(&entity.Admin{}, "id = ?", id).Error
	if err != nil {
		return fmt.Errorf("failed to delete admin: %w", err)
	}
	return nil
}

// 管理员查询
func (r *adminRepository) GetAllAdmins(ctx context.Context, limit, offset int) ([]entity.Admin, int64, error) {
	var admins []entity.Admin
	var total int64

	// 获取总数
	err := r.db.WithContext(ctx).Model(&entity.Admin{}).Count(&total).Error
	if err != nil {
		return nil, 0, fmt.Errorf("failed to count admins: %w", err)
	}

	// 获取分页数据
	query := r.db.WithContext(ctx).Order("created_at DESC")
	if limit > 0 {
		query = query.Limit(limit)
	}
	if offset > 0 {
		query = query.Offset(offset)
	}

	err = query.Find(&admins).Error
	if err != nil {
		return nil, 0, fmt.Errorf("failed to get admins: %w", err)
	}

	return admins, total, nil
}

func (r *adminRepository) GetAdminsByRole(ctx context.Context, role entity.AdminRole, limit, offset int) ([]entity.Admin, int64, error) {
	var admins []entity.Admin
	var total int64

	query := r.db.WithContext(ctx).Where("role = ?", role)

	// 获取总数
	err := query.Model(&entity.Admin{}).Count(&total).Error
	if err != nil {
		return nil, 0, fmt.Errorf("failed to count admins by role: %w", err)
	}

	// 获取分页数据
	query = query.Order("created_at DESC")
	if limit > 0 {
		query = query.Limit(limit)
	}
	if offset > 0 {
		query = query.Offset(offset)
	}

	err = query.Find(&admins).Error
	if err != nil {
		return nil, 0, fmt.Errorf("failed to get admins by role: %w", err)
	}

	return admins, total, nil
}

// 登录记录
func (r *adminRepository) UpdateLastLogin(ctx context.Context, adminID uuid.UUID) error {
	now := time.Now()
	err := r.db.WithContext(ctx).Model(&entity.Admin{}).
		Where("id = ?", adminID).
		Update("last_login", &now).Error
	if err != nil {
		return fmt.Errorf("failed to update last login: %w", err)
	}
	return nil
}

// 管理员统计
func (r *adminRepository) GetAdminCount(ctx context.Context) (int64, error) {
	var count int64
	err := r.db.WithContext(ctx).Model(&entity.Admin{}).Count(&count).Error
	if err != nil {
		return 0, fmt.Errorf("failed to get admin count: %w", err)
	}
	return count, nil
}
